#include "WatershedSegmenter.h"


WatershedSegmenter::WatershedSegmenter(void)
{
}


WatershedSegmenter::~WatershedSegmenter(void)
{
}


void WatershedSegmenter::setMarkers(const Mat& markerImage)
{
	markerImage.convertTo(this->markers,CV_32S);
	
}


cv::Mat WatershedSegmenter::process(const cv::Mat &image)
{
	watershed(image,this->markers);
	return this->markers;
}

void WatershedSegmenter::test(const cv::Mat &image) {
      // Apply watershed
      


	//cv::Mat image = cv::imread(argv[1]);
    cv::Mat binary;// = cv::imread(argv[2], 0);
    cv::cvtColor(image, binary, CV_BGR2GRAY);
    cv::threshold(binary, binary, 100, 255, THRESH_BINARY);

    imshow("originalimage", image);
    imshow("originalbinary", binary);

    // Eliminate noise and smaller objects
    cv::Mat fg;
    cv::erode(binary,fg,cv::Mat(),cv::Point(-1,-1),6);
    imshow("fg", fg);

    // Identify image pixels without objects
    cv::Mat bg;
    cv::dilate(binary,bg,cv::Mat(),cv::Point(-1,-1),6);
    cv::threshold(bg,bg,1, 128,cv::THRESH_BINARY_INV);
    imshow("bg", bg);

    // Create markers image
    cv::Mat markers(binary.size(),CV_8U,cv::Scalar(0));
    markers= fg+bg;
    imshow("markers", markers);

    // Create watershed segmentation object
    //WatershedSegmenter segmenter;
    this->setMarkers(markers);

    cv::Mat result = this->process(image);
    result.convertTo(result,CV_8U);
    imshow("final_result", result);

    cv::waitKey(0);
	
     
     }

void WatershedSegmenter::sobelTest(Mat& img)
{
	Mat I,X,Y,sobel,sobelImage;
	cvtColor(img,I,CV_BGR2GRAY);
	Sobel(I,X,CV_32F,1,0);
	Sobel(I,Y,CV_32F,0,1);

	//L1 norm
	sobel = abs(X)+abs(Y);


	//normalizzo
	double min,max;
	minMaxLoc(sobel,&min,&max);
	sobel.convertTo(sobelImage,CV_8U,-255./max,255);
	imshow("sobel",sobelImage);
	waitKey(0);

}